<template>
  <tree-select
    v-if="deptTreeData"
    ref="treeSelect"
    @treeSelect="handleSelect"
    @cancelSelect="handleCancelSelect"
    :placeholder="placeholder"
    :options="deptTreeData"
    :selectValue="selectValue"
    :multiple="multiple"
    :disabled="disabled"
    :clearable="clearable"
    @valueChange="valueChange"
  />
</template>

<script>
import TreeSelect from '@/components/ETreeSelect'
import { classifyList } from '@/api/eval'

export default {
  name: 'DeptSelect',
  components: {
    TreeSelect
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    selectValue: [String, Array], // 多选时为Array
    clearable: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: undefined
    },
    multiple: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 样式
    selectStyle: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      deptTreeData: []
    }
  },
  mounted() {
    classifyList().then(res => {
      let parentArr = []
      res.data.map(v => {
        if (!v.parentId) {
          parentArr.push(v)
        }
      })
      this.handleParentChild(parentArr, res.data)
      const arr = parentArr
      this.deptTreeData = this.handleData(arr)
    })
  },
  methods: {
    handleParentChild(arr1, arr2) {
      arr1.map(v => {
        v.children = []
        arr2.map(j => {
          if (v.evalTypeId === j.parentId) {
            v.children.push(j)
            if (v.children && v.children.length > 0) {
              this.handleParentChild(v.children, arr2)
            }
          }
        })
      })
    },
    handleData(arr) {
      arr.map(v => {
        v.id = v.evalTypeId
        v.label = v.evalTypeName
        if (v.children && v.children.length > 0) {
          this.handleData(v.children)
        } else {
          delete v.children
        }
      })
      return arr
    },
    reset() {
      this.$refs.treeSelect.reset()
    },
    handleSelect(node) {
      this.$emit('select', node)
    },
    handleCancelSelect(node) {
      this.$emit('cancelSelect', node)
    },
    valueChange(value) {
      this.$emit('valueChange', value)
    }
  },
  created() {
    this.value = this.selectValue
  }
}
</script>
